package com.alibaba.algo.utils;

import com.xxl.sso.core.conf.Conf;
import com.xxl.sso.core.user.XxlSsoUser;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName: UserContextUtils
 * @Description: 登录用户工具类
 * @Author: wugongzi
 * @Date: 2021/12/9 10:40
 * @Version: 1.0
 */
public class UserContextUtils {

    private UserContextUtils() {
    }

    /**
     * 获取当前登录用户
     *
     * @return
     */
    public static XxlSsoUser getCurrentUser() {
        if (null == RequestContextHolder.getRequestAttributes()) {
            return null;
        }
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (ObjectUtils.isEmpty(request) || ObjectUtils.isEmpty(request.getAttribute(Conf.SSO_USER))) {
            return null;
        }
        return (XxlSsoUser) request.getAttribute(Conf.SSO_USER);
    }

    public static String getCurrentUserName() {
        XxlSsoUser user = getCurrentUser();
        if (ObjectUtils.isEmpty(user)) {
            return null;
        }
        return user.getUsername();
    }
}
